//
//  BIDDeleteBill.m
//  theFifth
//
//  Created by 邵瑞 on 13-6-3.
//
//

#import "BIDDeleteBill.h"
#import "TheProjectCell.h"
#import "TreeViewNode.h"
#import "BIDTypesManager.h"
#import "BIDBillsLookoverManager.h"
#import "BIDUserInputViewController.h"
#import "MonthController.h"
#import "BIDDateView.h"
#import <QuartzCore/QuartzCore.h>
@interface BIDDeleteBill ()
{
       UISegmentedControl *billManagerSegmented;
       NSArray * title;
       NSInteger * selectedrow;
       BIDBillsLookoverManager * billsManager;
       BIDTypesManager * typeManager;
       //
       NSUInteger indentation;
       NSMutableArray *nodes;
       TreeViewNode *secondLevelNode1;
       TreeViewNode * firstLevelNode1;
       NSInteger inYearmonthBills;
       NSInteger monthBillsString;
       NSInteger yearBills;
       ///

}
@property (strong,nonatomic) NSMutableArray * listarray;
@property (strong,nonatomic) NSMutableArray * listSection;
//////////////
@property (nonatomic, retain) NSMutableArray *displayArray;

- (void)expandCollapseNode:(NSNotification *)notification;

- (void)fillDisplayArray;
- (void)fillNodeWithChildrenArray:(NSArray *)childrenArray;

- (void)fillNodesArray;
- (NSArray *)fillChildrenForNode;

- (IBAction)expandAll:(id)sender;
- (IBAction)collapseAll:(id)sender;
@end

@implementation BIDDeleteBill
@synthesize listarray =_listarray;
@synthesize listSection =_listSection;
/////////
@synthesize displayArray;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
       self.navigationController.navigationBarHidden= NO;
       UIBarButtonItem *itern=  [[UIBarButtonItem alloc] initWithTitle:@"删除" style:0 target:self action:@selector(tableViewEdit:)];
        UIBarButtonItem *iternleft=  [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:self action:@selector(backUpPage:)];
//            itern=  [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:self action:@selector(backUpPage:)];

              if (self.tabBarController.navigationItem.rightBarButtonItem==nil)
                  {
                  self.tabBarController.navigationItem.rightBarButtonItem=itern;
                  }
       
self.tabBarController.navigationItem.leftBarButtonItem = iternleft;
    self.tabBarController.navigationItem.rightBarButtonItem = itern;

          title  =[[NSArray alloc]initWithObjects:@"插入",nil];
       billManagerSegmented = [[UISegmentedControl alloc] initWithItems:title];
       billManagerSegmented.frame= CGRectMake(130, 5.0, 70, 35.0);

       billManagerSegmented.backgroundColor = [UIColor clearColor];
       billManagerSegmented.tag=0;
//       self.navigationController.navigationBar = [[UIBarButtonItem alloc] initWithCustomView:billManagerSegmented];
       [self.navigationController.navigationBar addSubview:billManagerSegmented];
        [billManagerSegmented addTarget:self action:@selector(selectaaa:) forControlEvents:UIControlEventValueChanged];
       

  }
-(void)backUpPage:(id)send
{

       UIView * view = self.navigationController.view;
       [self pageCurlAnmation:view];
       [self.navigationController popViewControllerAnimated:NO];

}
-(void)pageCurlAnmation:(UIView*)view
{
    CATransition *tran=[CATransition animation];
//    tran.type=@"pageCurl";//pageCurl／flip


       tran.type =@"pageUnCurl";
//       tran.subtype = @"fromleft";

    tran.duration=1.5;
    tran.delegate=self;
    [view.layer addAnimation:tran forKey:@"ads"];
}

-(void)viewWillDisappear:(BOOL)animated
{
       [billManagerSegmented removeFromSuperview];
       self.tabBarController.navigationItem.rightBarButtonItem=nil;
}


-(void)selectaaa:(id)sender
{
      
       switch (billManagerSegmented.selectedSegmentIndex)
       {
              case 0:
              [self nextPage];
              break;
              default:
              break;

       }

}
-(void)nextPage
{
       BIDUserInputViewController * nextview = [[BIDUserInputViewController alloc] init];
       [self.navigationController pushViewController:nextview animated:YES];

}
- (void)tableViewEdit:(id)sender
{
   // [self.tableView setEditing:!self.tableView.editing animated:YES];
    if (self.tableView.editing)
      {
  self.tableView.editing=NO;
      }
     else
     {self.tableView.editing=YES;};
}

- (void)viewDidLoad
{
       [super viewDidLoad];

          billsManager = [BIDBillsLookoverManager shareBillsLookoverManager];
       typeManager = [BIDTypesManager shareTypesManager];
       _listarray=  [typeManager totalYearBills];
       [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(expandCollapseNode:) name:@"ProjectTreeNodeButtonClicked" object:nil];
       [self fillNodesArray];
       [self fillDisplayArray];
       [self.tableView reloadData];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
//     self.navigationItem.rightBarButtonItem = self.editButtonItem;


}
-(void)viewDidUnload
{
 [[NSNotificationCenter defaultCenter]removeObserver:self];
    [super viewDidUnload];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}
//删除按钮
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
       return @"删除";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.

    return self.displayArray.count;
    

    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
       static NSString *CellIdentifier = @"treeNodeCell";
           UINib *nib = [UINib nibWithNibName:@"ProjectCell" bundle:nil];
           [tableView registerNib:nib forCellReuseIdentifier:CellIdentifier];
              UILabel * monthLable = [[UILabel alloc] init];

              monthLable.frame = CGRectMake(90, 5, 220,40);
              monthLable.tag = 11;
              monthLable.font  =[UIFont fontWithName:@"Arial" size:15];
              monthLable.textAlignment = NSTextAlignmentCenter;
              monthLable.textColor = [UIColor blackColor];
              //        lable.tintColor = [UIColor  whiteColor];
              monthLable.backgroundColor = [UIColor whiteColor];
              monthLable.userInteractionEnabled = YES;

 
           TheProjectCell *cell = (TheProjectCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
           TreeViewNode *node = [self.displayArray objectAtIndex:indexPath.row];
//           cell.treeNode = node;//有这句代码子节点能够展开子节点，没有则不会
    cell.cellLabel.text = node.nodeObject;
       NSString * yearCountAmount = [ NSString stringWithFormat:@"%@",node.nodeObject];
              NSInteger yearCounMoneys = [billsManager totalAmountCountYearSpent:yearCountAmount.integerValue];
       NSString * getCount = [NSString stringWithFormat:@"年总金额为:%d",yearCounMoneys];
           if (node.isExpanded)
            {
              [cell setTheButtonBackgroundImage:nil andYearCount:nil];
           }
           else {
                     [cell setTheButtonBackgroundImage:nil andYearCount:nil];
           }
       [cell addSubview:monthLable];
       monthLable.textColor = [UIColor blackColor];
       monthLable.text =  getCount;
   //    cell.contentView.backgroundColor=[UIColor lightGrayColor];
       cell.selectionStyle = UITableViewCellSelectionStyleGray;
       cell.accessoryType= UITableViewCellAccessoryDetailDisclosureButton;
//       UITableViewCellAccessoryDetailDisclosureButton;
           [cell setNeedsDisplay];


    return cell;
}


-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
       return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{


       NSString *yearstring;
       for (TreeViewNode *node in nodes) 
       {
//              yearstring = node.nodeObject;
//              NSLog(@"%@",yearstring);
//              yearBills = yearstring.integerValue;
              if (node.isExpanded == YES)
               {
                     node =[self.displayArray objectAtIndex:indexPath.row];
                    yearstring = node.nodeObject;
                   yearBills = yearstring.integerValue;
                     NSLog(@"%d",yearBills);
              }
               
               
              break;
       }

       [self uialetrview];

       [self reference];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
       MonthController * nextPage =[[MonthController alloc] initWithNibName:@"MonthController" bundle:nil];
       
        nextPage.year=[[[typeManager totalYearBills] objectAtIndex:indexPath.row] integerValue];
       [self.navigationController pushViewController:nextPage animated:YES];

}
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
//    NSInteger row = indexPath.row;
//    if (row == 0)
//    {
       BIDDateView* nextpage = [[BIDDateView alloc] init];
              nextpage.detailYear = [[[typeManager totalYearBills] objectAtIndex:indexPath.row] integerValue];;
       [self.navigationController pushViewController:nextpage animated:YES];
       
    //}
}

-(void)uialetrview
{

       NSString *deleteyear = [NSString stringWithFormat:@"确定删除%d年的账单",yearBills];
       UIAlertView * alter = [[UIAlertView alloc] initWithTitle:@"警告" message:deleteyear delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
       [alter show];
       [alter release];
}
-(void)reference
{
       _listarray=  [typeManager totalYearBills];
//               NSMutableArray * arrays
// =[typeManager aYearOfMonthTotalBills:inYearmonthBills];
       [self fillNodesArray];//add child
       [self fillDisplayArray];
       [self displayArray];
       [self.tableView reloadData];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
        switch (buttonIndex)
  {
        case 0:
              [self deleteYearOrMonth];
              [self reference];
              NSLog(@"Cancel Button Pressed");
            break;
        case 1:
            NSLog(@"Button 1 Pressed");
            break;
                default:
            break;
            }
      
}
-(void)deleteYearOrMonth
{     
              [typeManager deleteAYearBill:yearBills];
              NSLog(@"%d,%d",inYearmonthBills,yearBills);

       
       
       
}
-(void)fillNodesArray
{
       nodes=[[NSMutableArray alloc] init];
       for (int i=0; i<_listarray.count; i++)
       {
              firstLevelNode1= [[TreeViewNode alloc] init];
              firstLevelNode1.nodeLevel = 0;
              firstLevelNode1.isExpanded = YES;
              NSInteger index = [[_listarray objectAtIndex:i] integerValue];
              inYearmonthBills = index;
              NSString *yearStr = [NSString stringWithFormat:@"%d",index];
              firstLevelNode1.nodeObject = yearStr;
              firstLevelNode1.nodeChildren = [[self fillChildrenForNode] mutableCopy];
              [nodes addObject:firstLevelNode1];
              NSLog(@"%@",nodes);
       }

}

-(NSArray *)fillChildrenForNode
{
       NSMutableArray *childrenArray = [[NSMutableArray alloc] init];
               NSMutableArray * arrays=[typeManager aYearOfMonthTotalBills:inYearmonthBills];
         for (int j=0; j<arrays.count; j++)
        {
              secondLevelNode1 = [[TreeViewNode alloc]init];
              secondLevelNode1.nodeLevel = 1;
              NSInteger index = [[arrays objectAtIndex:j] integerValue];
              NSString *MonthStr = [NSString stringWithFormat:@"%d",index];
              secondLevelNode1.nodeObject = MonthStr;
              [childrenArray addObject:secondLevelNode1];
              NSLog(@"%@",childrenArray);
       }

       return childrenArray;


}

//节点展开时通知调用此处

-(void)expandCollapseNode:(NSNotification *)notification
{
       _listarray=  [typeManager totalYearBills];
       [self fillDisplayArray];
    [self.tableView reloadData];



}
-(void)fillNodeWithChildrenArray:(NSArray *)childrenArray
{
       for (TreeViewNode *node in childrenArray)
       {
              [self.displayArray addObject:node];
               if (node.isExpanded==NO)
               {
                   [self fillNodeWithChildrenArray:node.nodeChildren];
               }
       }
}
-(void)fillDisplayArray
{
  self.displayArray = [[NSMutableArray alloc]init];
    for (TreeViewNode *node in nodes)
     {
        [self.displayArray addObject:node];
        if (node.isExpanded==NO)
        {
            [self fillNodeWithChildrenArray:node.nodeChildren];
        }
    }
       [self.tableView reloadData];
}

-(IBAction)collapseAll:(id)sender
{

       for (TreeViewNode *treeNode in nodes)
       {
              treeNode.isExpanded = NO;
       }
       [self fillDisplayArray];
       [self.tableView reloadData];

}
-(IBAction)expandAll:(id)sender
{

   [self fillNodesArray];
    [self fillDisplayArray];
    [self.tableView reloadData];

}

//点击某一行做某事




#pragma mark - Table view delegate
- (void)handleSelection:(id)sender
{
	NSLog(@"URBSegmentedControl: value changed");
}


@end
